package com.gmcloud.common.excel.aspest;

import com.gmcloud.common.excel.annotation.ResponseExcel;
import com.gmcloud.common.excel.processor.NameProcessor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Objects;

/**
 * @author zl
 * @since  2022/9/20 20:00
 * @BelongsProject gm-cloud
 * @BelongsPackage com.gmcloud.common.aspest
 * @description 动态名称
 */
@Aspect
public class DynamicNameAspect {

    public static final String EXCEL_NAME_KEY = "__EXCEL_NAME_KEY__";

    private final NameProcessor processor;

    public DynamicNameAspect(NameProcessor processor) {
        this.processor = processor;
    }


    @Before("@annotation(excel)")
    public void around(JoinPoint point, ResponseExcel excel) {
        // 获取方法的参数类型和返回类型
        MethodSignature ms = (MethodSignature) point.getSignature();

        String name = excel.name();
        // 当配置的 excel 名称为空时，取当前时间
        if (!StringUtils.hasText(name)) {
            name = LocalDateTime.now().format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL));
        } else {
            name = processor.doDetermineName(point.getArgs(), ms.getMethod(), name);
        }

        RequestAttributes requestAttributes= RequestContextHolder.getRequestAttributes();
        Objects.requireNonNull(requestAttributes).setAttribute(EXCEL_NAME_KEY,name,RequestAttributes.SCOPE_REQUEST);
    }

}
